# Filters added to this controller apply to all controllers in the application.
# Likewise, all the methods added will be available for all controllers.

class ApplicationController < ActionController::Base
  helper :all # include all helpers, all the time

  protect_from_forgery # See ActionController::RequestForgeryProtection for details

  # Scrub sensitive parameters from your log
  filter_parameter_logging :cpf, :email, :password, :password_confirmation

  # Devise
  before_filter :check_recaptcha_for_devise, :only => :create
  before_filter :authenticate_user!

  # Exception
  rescue_from Exception, :with => :render_exceptions

  # Restfulx-Devise compat.
  def after_sign_in_path_for(resource)
    if request.format == Mime::FXML
      super + "perfil.fxml"
    else
      super
    end
  end

  def after_sign_out_path_for(resource_or_scope)
    if request.format == Mime::FXML
      {:status => 200}
    else
      super
    end
  end

  # Declarative Authorization
  filter_access_to :all

  def permission_denied
    flash[:error] = "Permissão negada."
    redirect_to root_path
  end

  private

  def render_exceptions(exception)
    respond_to do |format|
      format.html do
        logger.debug exception.inspect
        render :file => 'public/500.html', :status => 500
      end
      format.fxml { render :fxml => exception }
    end
  end

  def check_recaptcha_for_devise
    if controller_name == 'registrations'
      build_resource
      captcha_ok = verify_recaptcha(:model => resource, :message => "Verificação de palavras não confere")
      render_with_scope :new unless captcha_ok
    end
  end

end